<template>
	<div class="login-container">
		<!-- 品牌标识区域 -->
		<div class="brand-header">
			<div class="brand-logo">HT</div>
			<div class="brand-text">
				{{ getThemeConfig.globalTitle }}
				<span class="brand-subtitle">化工智能管理系统</span>
			</div>
		</div>

		<!-- 左侧插图区域 -->
		<div class="login-illustration">
			<div class="illustration-content">
				<!-- 化工设备等距插图 -->
				<div class="isometric-illustration">
					<!-- 主要化工设备 - 反应釜 -->
					<div class="main-reactor">
						<div class="reactor-body"></div>
						<div class="reactor-pipes"></div>
						<div class="control-panel"></div>
					</div>

					<!-- 工业监控设备 -->
					<div class="monitoring-devices">
						<div class="device device-1">🔬</div>
						<div class="device device-2">📡</div>
						<div class="device device-3">⚗️</div>
						<div class="device device-4">🔧</div>
					</div>

					<!-- 数据传输线 -->
					<div class="data-lines">
						<div class="line line-1"></div>
						<div class="line line-2"></div>
						<div class="line line-3"></div>
					</div>
				</div>

				<!-- 文字描述 -->
				<div class="illustration-text">
					<h2 class="welcome-title">智慧化工</h2>
					<p class="welcome-subtitle">数字化转型 · 智能化管理 · 安全生产</p>

					<!-- 行业特色功能 -->
					<div class="industry-features">
						<div class="feature">
							<div class="feature-icon">🛡️</div>
							<span class="feature-text">安全监控</span>
						</div>
						<div class="feature">
							<div class="feature-icon">📊</div>
							<span class="feature-text">数据分析</span>
						</div>
						<div class="feature">
							<div class="feature-icon">⚙️</div>
							<span class="feature-text">智能控制</span>
						</div>
					</div>
				</div>
			</div>
		</div>

		<!-- 右侧登录表单区域 -->
		<div class="login-form-container" :class="{ 'form-loading': cardLoading }">
			<!-- 简约头部 -->
			<div class="login-header">
				<div class="logo-section">
					<img :src="logoMini" alt="logo" class="logo-image" />
					<h1 class="system-title">{{ getThemeConfig.globalTitle }}</h1>
				</div>

				<!-- 返回按钮 -->
				<div class="login-actions" v-if="showWechatLogin || showBindPhone">
					<template v-if="showWechatLogin">
						<el-tooltip content="返回账号登录" placement="left">
							<div class="back-icon" @click="showWechatLogin = false">
								<el-icon>
									<Back />
								</el-icon>
							</div>
						</el-tooltip>
					</template>
					<template v-if="showBindPhone">
						<el-tooltip content="返回账号登录" placement="left">
							<div class="back-icon" @click="handleBackToLogin">
								<el-icon>
									<Back />
								</el-icon>
							</div>
						</el-tooltip>
					</template>
				</div>
			</div>

			<!-- 登录表单内容 -->
			<div class="login-form-content">
				<transition name="fade" mode="out-in">
					<div v-if="showWechatLogin" key="wechat" class="login-content">
						<Wechat @loading-change="handleLoadingChange" />
					</div>
					<div v-else-if="showBindPhone" key="bind-phone" class="login-content">
						<BindPhone
							:Code="wechatAuthInfo.code"
							:State="wechatAuthInfo.state"
							:WechatKey="wechatAuthInfo.WechatKey"
							@loading-change="handleLoadingChange"
							@back="handleBackToLogin"
						/>
					</div>
					<div v-else key="account" class="login-content">
						<h2 class="login-title">开始登录</h2>
						<p class="login-subtitle">您好！欢迎登录了~</p>

						<el-tabs v-model="loginType" class="login-tabs">
							<el-tab-pane label="账号密码" name="account">
								<div class="tab-content-wrapper">
									<transition name="fade-slide" mode="out-in">
										<keep-alive>
											<Account v-show="loginType === 'account'" @loading-change="handleLoadingChange" />
										</keep-alive>
									</transition>
								</div>
							</el-tab-pane>
							<el-tab-pane v-if="loginConfig.EnableSmsLogin" label="手机验证码" name="phone">
								<div class="tab-content-wrapper">
									<transition name="fade-slide" mode="out-in">
										<keep-alive>
											<Phone v-show="loginType === 'phone'" @loading-change="handleLoadingChange" />
										</keep-alive>
									</transition>
								</div>
							</el-tab-pane>
						</el-tabs>

						<!-- 第三方登录 -->
						<div class="third-party-login">
							<p class="third-party-title">第三方账号登录</p>
							<div class="social-login-icons">
								<div class="social-icon wechat" title="微信登录" @click="handleGetWechatUrl" v-if="loginConfig.EnableWechatLogin">
									<svg viewBox="0 0 24 24" width="20" height="20" fill="#07C160">
										<path
											d="M8.691 2.188C3.891 2.188 0 5.476 0 9.53c0 2.212 1.17 4.203 3.002 5.55a.59.59 0 0 1 .213.665l-.39 1.48c-.019.07-.048.141-.048.213 0 .163.13.295.29.295a.326.326 0 0 0 .167-.054l1.903-1.114a.864.864 0 0 1 .717-.098 10.16 10.16 0 0 0 2.837.403c.276 0 .543-.027.811-.05-.857-2.578.157-4.972 1.932-6.446 1.703-1.415 3.882-1.98 5.853-1.838-.576-3.583-4.196-6.348-8.596-6.348zM5.785 5.991c.642 0 1.162.529 1.162 1.18 0 .659-.52 1.188-1.162 1.188-.642 0-1.162-.529-1.162-1.188 0-.651.52-1.18 1.162-1.18zm5.813 0c.642 0 1.162.529 1.162 1.18 0 .659-.52 1.188-1.162 1.188-.642 0-1.162-.529-1.162-1.188 0-.651.52-1.18 1.162-1.18zm4.025 2.357c-1.378 0-2.676.527-3.611 1.422-.845.809-1.379 1.897-1.379 3.135 0 2.49 2.418 4.51 5.4 4.51.609 0 1.195-.08 1.746-.218a.818.818 0 0 1 .678.093l1.429.837a.24.24 0 0 0 .125.04c.118 0 .216-.097.216-.218 0-.053-.023-.103-.036-.156l-.292-1.102a.442.442 0 0 1 .159-.498c1.37-1.008 2.265-2.504 2.265-4.188 0-3.04-2.896-5.507-6.47-5.507zm-2.118 2.956c.484 0 .875.4.875.892 0 .492-.391.892-.875.892s-.875-.4-.875-.892c0-.492.391-.892.875-.892zm4.236 0c.484 0 .875.4.875.892 0 .492-.391.892-.875.892s-.875-.4-.875-.892c0-.492.391-.892.875-.892z"
										/>
									</svg>
								</div>
							</div>
						</div>

						<!-- 注册链接 -->
						<div class="register-link">
							<span>还没有账号？</span>
							<span class="register-btn" @click="handleForgotPassword">立即注册</span>
						</div>
					</div>
				</transition>
			</div>
		</div>

		<!-- 版权信息 -->
		<div class="copyright">
			<p>© 2025 {{ getThemeConfig.globalViceTitle }}</p>
		</div>
	</div>
</template>

<script setup lang="ts" name="loginIndex">
import { defineAsyncComponent, onMounted, computed, ref, markRaw } from 'vue';
import { storeToRefs } from 'pinia';
import { useThemeConfig } from '/@/stores/themeConfig';
import { useSiteConfig } from '/@/stores/siteConfig';
import { NextLoading } from '/@/utils/loading';
import { ElMessage } from 'element-plus';
import { Back } from '@element-plus/icons-vue';
import logoMini from '/@/assets/logo.png';
import useLoginApi from '/@/api/login';

import { Local } from '/@/utils/storage';

// 引入组件
const Account = markRaw(defineAsyncComponent(() => import('/@/views/login/component/account.vue')));
const Phone = markRaw(defineAsyncComponent(() => import('/@/views/login/component/phone.vue')));
const Wechat = markRaw(defineAsyncComponent(() => import('/@/views/login/component/wechat.vue')));
const BindPhone = markRaw(defineAsyncComponent(() => import('/@/views/login/component/bingPhone.vue')));

// 定义变量内容
const storesThemeConfig = useThemeConfig();
const storesSiteConfig = useSiteConfig();
const { themeConfig } = storeToRefs(storesThemeConfig);
const loginApi = useLoginApi();
const cardLoading = ref(false);
const loginType = ref('account');
const showWechatLogin = ref(false);
const showBindPhone = ref(false);
const wechatAuthInfo = ref<{
	code: string;
	state: string;
	WechatKey: any;
}>({
	code: '',
	state: '',
	WechatKey: '',
});

// 登录配置 - 使用全局站点配置
const loginConfig = computed(() => ({
	EnableSmsLogin: storesSiteConfig.isSmsLoginEnabled,
	EnableWechatLogin: storesSiteConfig.isWechatLoginEnabled,
}));

// 获取布局配置信息
const getThemeConfig = computed(() => {
	return themeConfig.value;
});

// 处理加载状态变化
const handleLoadingChange = (loading: boolean) => {
	cardLoading.value = loading;
};

// 处理忘记密码
const handleForgotPassword = () => {
	ElMessage.warning('请联系管理员');
};

//获取微信登录地址
const handleGetWechatUrl = async () => {
	// 打开微信扫码登录二维码
	showWechatLogin.value = true;
	try {
		const res = await loginApi.getWechatUrl();
		if (res.Code === 200) {
			window.location.href = res.Data;
		} else {
			ElMessage.error(res.Message);
		}
	} catch (error) {
		console.log(error);
	}
};

// 处理微信登录回调
const handleWechatCallback = async () => {
	// 从当前URL中获取参数
	const url = window.location.href;
	const urlObj = new URL(url);

	// 获取code和state参数
	const code = urlObj.searchParams.get('code');
	const state = urlObj.searchParams.get('state');

	if (code && state) {
		try {
			const res = await loginApi.signInWechatLogin({ Code: code, State: state });
			if (res.Code === 200) {
				// await handleLoginSuccess(res.Data.access_token, emit);
				Local.set('token', res.Data.access_token);
				window.location.replace('/');
				ElMessage.success('登录成功');
				return;
			} else if (res.Code === 1) {
				const WechatKey = res.Data;
				// 需要绑定手机号，保存参数供后续使用
				wechatAuthInfo.value = { code, state, WechatKey };
				showWechatLogin.value = false;
				showBindPhone.value = true;
				ElMessage.warning(res.Message || '需要绑定手机号');
			} else {
				ElMessage.error(res.Message || '登录失败');
			}
		} catch (error) {
			console.error('微信登录失败:', error);
			ElMessage.error('登录失败，请重试');
		}
	}
};

// 在页面加载时检查微信登录回调
onMounted(() => {
	NextLoading.done();
	// 检查URL中是否包含code和state参数
	const url = window.location.href;
	if (url.includes('code=') && url.includes('state=')) {
		handleWechatCallback();
	}
});

const handleBackToLogin = () => {
	showBindPhone.value = false;
	showWechatLogin.value = false;
	// 清除URL中的参数
	window.history.replaceState({}, '', window.location.pathname);
};
</script>

<!-- 样式由 src/theme/login.scss 提供 -->
